package com.lx.chong.utils;

import org.apache.commons.lang.RandomStringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: whh
 * @date: 2018/2/27
 */
public class CodeUtil {

    /**
     * 生成一个时间段的不重复随机码
     * @param count 随机码个数
     * @param length 随机值长度
     * @return
     */
    public static List<String> getCommonCode(long count, int length) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateStr = format.format(date);
        List<String> list = new ArrayList<>();
        Set<String> random = new HashSet<>();
        for (Integer i = 0; i < count; i++) {
            random.add(dateStr + RandomStringUtils.randomNumeric(length));
        }
        // 有重复
        if(random.size() < count) {
            while (true) {
                random.add(dateStr + RandomStringUtils.randomNumeric(length));
                if(random.size() >= count) {
                    list.clear();
                    list.addAll(random);
                    return list;
                }
            }
        }
        else {
            list.clear();
            list.addAll(random);
        }
        return list;
    }

}
